/**
 * 观察者模式：被观察者发生变化时，会通知观察者更新，类似监听
 * 被观察者需要记录观察者
*/

// 被观察者
class Subject {
    constructor(name) {
        this.name = name
        this.observes = []
        this.state = '开心'
    }
    attach(o) {
        this.observes.push(o)
    }
    setState(newState) {
        this.state = newState
        this.observes.forEach(o => o.update(newState))
    }
}
// 观察者
class Observer {
    constructor(name) {
        this.name = name
    }
    update(s) {
        console.log(this.name, s);
    }
}

const baby = new Subject('baby')

const f = new Observer('father')
const m = new Observer('mother')
baby.attach(m)
baby.attach(f)

setTimeout(() => {
    baby.setState('不开心')
}, 500)